/**============================================================================
 Confidential Information - Limited distribution to authorized persons only.
 This software is protected as an unpublished work under the U.S. Copyright
 Act of 1976.

 Copyright (c) 2011, BluePhoenix Solutions, Inc. All rights reserved.
 ----------------------------------------------------------------------------
 file......: BaseTableModel.java
 Author....: Vyacheslav Kovalyov
 Created...: 27.10.11

 Description:

 ============================================================================*/
package ru.monyag.pred.swing.ui.table;

import ru.monyag.pred.swing.ui.ITableModel;

import javax.swing.table.DefaultTableModel;
import java.util.List;

/**
 * @author Vyacheslav Kovalyov
 * @version 1.0
 */
public abstract class BaseTableModel<T> extends DefaultTableModel implements ITableModel<T> {

    public BaseTableModel(TableModelInfo model) {
        super(DEFAULT_ROWS_COUNT, model.getColumnsCount());
        setColumnIdentifiers(model.getColumnNames());
        this.model = model;
    }

    @Override
    public void updateRow(T object) {
        int rowIndex = data.indexOf(object);
        removeRow(rowIndex);
        insertRow(rowIndex, createRow(object));
    }

    @Override
    public T getRowObject(int row) {
        if (data == null || data.size() - 1 < row) {
            return null;
        }
        return data.get(row);
    }

    @Override
    public void setData(List<T> data) {

        clean();
        this.data = data;
        for (T object : data) {
            addRow(createRow(object));
        }
    }

    private Object[] createRow(T object) {
        Object cols[] = new Object[getColumnCount()];
        for (int i = 0; i < getColumnCount(); i++) {
            cols[i] = getColumnMapper().getValueAt(object, i);
        }

        return cols;
    }

    private void clean() {
        for (int i = 0; i < getRowCount(); i++) {
            removeRow(i);
        }
    }

    @Override
    public TableModelInfo getModelInfo() {
        return model;
    }

    protected abstract IColumnMapper<T> getColumnMapper();

    private static final int DEFAULT_ROWS_COUNT = 0;

    private TableModelInfo model;
    private List<T> data;
}
